import express from 'express'
import {
  Nuxt,
  Builder
} from 'nuxt'
import _ from 'lodash'
import Qs from 'querystring'
import api from './api'
import bodyParser from 'body-parser'
import myConfig from 'config'
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
const app = express()
import admin from './admin'
let jsonParser = bodyParser.json({
  limit: '50mb'
})
let urlPaser = bodyParser.urlencoded({
  extended: true,
  limit: '50mb'
})
app.set('port', port)
app.use('/_nuxt',express.static('.nuxt/dist'))
app.use(myConfig.get('admin.route'),admin)
// Import API Routes
app.use('/api', jsonParser, urlPaser, function (req, res, next) {
  req.body = _.assign({}, _.cloneDeep(req.query), _.cloneDeep(req.body));
  next();
}, api)
// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

// Init Nuxt.js
const nuxt = new Nuxt(config)

// Build only in dev mode
if (config.dev) {
  const builder = new Builder(nuxt)
  builder.build()
}

// Give nuxt middleware to express
app.use(nuxt.render)

// Listen the server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console